// app/service/organization_service.js
'use strict';

const { Service } = require('egg');

class OrganizationService extends Service {
  // 获取组织列表
  async getOrganizations({ page, limit, name, status }) {
    const { ctx } = this;
    const offset = (page - 1) * limit;

    const where = {};
    if (name) {
      where.name = { [ctx.app.Sequelize.Op.like]: `%${name}%` };
    }
    if (status !== undefined) {
      where.status = status;
    }

    const { rows, count } = await ctx.model.OrganizationModel.findAndCountAll({
      where,
      limit,
      offset,
      order: [['created_at', 'DESC']]
    });

    return {
      list: rows,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    };
  }

  // 获取组织详情
  async getOrganization(id) {
    const { ctx } = this;
    return await ctx.model.OrganizationModel.findByPk(id, {
      include: [
        {
          model: ctx.model.UserModel,
          as: 'users',
          through: { attributes: ['role'] }
        }
      ]
    });
  }

  // 创建组织
  async createOrganization(organizationData) {
    const { ctx } = this;
    return await ctx.model.OrganizationModel.create(organizationData);
  }

  // 更新组织
  async updateOrganization(id, organizationData) {
    const { ctx } = this;
    const organization = await ctx.model.OrganizationModel.findByPk(id);
    if (!organization) {
      throw new Error('组织不存在');
    }
    return await organization.update(organizationData);
  }

  // 删除组织
  async deleteOrganization(id) {
    const { ctx } = this;
    const organization = await ctx.model.OrganizationModel.findByPk(id);
    if (!organization) {
      throw new Error('组织不存在');
    }
    return await organization.destroy();
  }

  // 获取用户所属的组织
  async getUserOrganizations(userId) {
    const { ctx } = this;
    const user = await ctx.model.UserModel.findByPk(userId, {
      include: [{
        model: ctx.model.OrganizationModel,
        as: 'organizations',
        through: { attributes: ['role'] }
      }]
    });
    
    return user ? user.organizations : [];
  }

  // 添加用户到组织
  async addUserToOrganization(userId, organizationId, role) {
    const { ctx } = this;
    
    // 检查用户和组织是否存在
    const user = await ctx.model.UserModel.findByPk(userId);
    const organization = await ctx.model.OrganizationModel.findByPk(organizationId);
    
    if (!user) {
      throw new Error('用户不存在');
    }
    
    if (!organization) {
      throw new Error('组织不存在');
    }
    
    // 添加用户到组织
    return await ctx.model.UserOrganizationModel.findOrCreate({
      where: { userId, organizationId },
      defaults: { userId, organizationId, role }
    });
  }

  // 从组织移除用户
  async removeUserFromOrganization(userId, organizationId) {
    const { ctx } = this;
    return await ctx.model.UserOrganizationModel.destroy({
      where: { userId, organizationId }
    });
  }
}

module.exports = OrganizationService;